﻿using System;
using System.Reflection;
using ApiGateway.Model;
using HttpApiGateway.Collect;
using HttpApiGateway.FileUp.Interface;
using HttpApiGateway.Interface;
using HttpApiGateway.Model;
using RpcHelper;

namespace HttpApiGateway.FileUp
{
    internal class BlockUpApi : IHttpApi
    {
        protected readonly FuncParam _Param;
        private readonly Type _SourceType;

        public string ApiName => this._SourceType.FullName;

        public string ApiUri { get; }

        public MethodInfo Source => null;

        public BlockUpApi(ApiModel model, FuncParam param)
        {
            this._SourceType = model.Type;
            this._Param = param;
            this.ApiUri = model.ApiUri;
        }

        public void ExecApi(IService service)
        {
            IUpBlockFile api = UnityCollect.GetUpTask(this.ApiName);
            IBlockUpTask task = null;
            try
            {
                task = BlockUpCollect.Add(service, api);
                task.Load(service);
                service.Reply(task.TaskId);
            }
            catch (Exception e)
            {
                if (task != null)
                {
                    BlockUpCollect.Remove(task.TaskId);
                }
                ErrorException error = ErrorException.FormatError(e);
                error.SaveLog("Gateway");
                service.ReplyError(error.ToString());
            }
        }

        public void RegApi(IApiRoute route)
        {
            ApiFuncBody param = new ApiFuncBody
            {
                PostParam = new ApiPostParam[] {
                    new ApiPostParam
                    {
                        Name = this._Param.Name,
                        PostType = this._Param.DataType,
                        ReceiveMethod = this._Param.ReceiveMethod,
                        ParamIndex = 0
                    }
                },
                ApiType = route.ApiType,
                UpConfig = route.UpCheck.ToUpSet(),
                Source = _SourceType,
                IsAccredit = route.IsAccredit,
                Method = null,
                Prower = route.Prower,
                ApiUri = route.ApiUri
            };
            ApiGatewayService.RegApi(param);
        }

        public bool VerificationApi()
        {
            return true;
        }
    }
}
